package com.xuecheng.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*
 * es的配置类
 */
@Configuration
public class ElasticSearchConfig {

    // 读取配置文件的值
    @Value("${xuecheng.elasticsearch.hostlist}")
    private String hostlist;

    // 注册es的高级客户端
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 解析hostlist配置信息
        String[] split = hostlist.split(",");
        // 创建HttpHost数组，其中存放es主机和端口的配置信息
        HttpHost[] httpHost = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String item = split[i];
            String host = item.split(":")[0];// 主机
            int port = Integer.parseInt(item.split(":")[1]);// 端口
            httpHost[i] = new HttpHost(host, port, "http");
        }
        // 创建客户端
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(httpHost));
        return restHighLevelClient;
    }

    // 注册es客户端，主要针对低级版本
    @Bean
    public RestClient restClient() {
        // 解析hostlist配置信息
        String[] split = hostlist.split(",");
        // 创建HttpHost数组，其中存放es主机和端口的配置信息
        HttpHost[] httpHost = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String item = split[i];
            String host = item.split(":")[0];// 主机
            int port = Integer.parseInt(item.split(":")[1]);// 端口
            httpHost[i] = new HttpHost(host, port, "http");
        }
        // 创建客户端
        RestClient restClient = RestClient.builder(httpHost).build();
        return restClient;
    }

}
